package com.ebelter.test01.module.dj8module;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Message;
import com.ebelter.btcomlib.models.bluetooth.base.BlueManager;
import com.ebelter.btcomlib.models.bluetooth.base.BlueScan;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IBlueStationListener;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IConnectStationCallback;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IScanCallback;
import com.ebelter.btcomlib.models.bluetooth.products.dianji8.Dj8Constant;
import com.ebelter.btcomlib.models.bluetooth.products.dianji8.Dj8ManagerBle;
import com.ebelter.btcomlib.models.bluetooth.products.dianji8.bean.Dj8MesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.dianji8.bean.Dj8ScaleUserInfo;
import com.ebelter.btcomlib.models.bluetooth.products.dianji8.bean.Dj8Users;
import com.ebelter.btcomlib.models.bluetooth.products.dianji8.interfaces.Dj8MeasureCallback;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.log.LogUtils;


public class Dj8ScaleBleManager extends BaseHandle {

    private static final String TAG = "Dj8ScaleBleManager";
    /**
     * 当前需要连接的设备
     */
    private BluetoothDevice device;


    //蓝牙扫描器
    private BlueScan mBlueScan;
    private Dj8ManagerBle mDj8ManagerBle;
    private Dj8ScaleUserInfo dj8ScaleUserInfo;//当前使用用户的信息

    public Dj8ScaleBleManager(Context context) {
        super(context);
        init(context);
        addBluetoothStationListener(mIBlueStationListener);
    }


    private boolean isWorkFlag;


    private void setUpdateUser2Front(boolean needUpdateUserInfo2Front){
        if (mDj8ManagerBle!=null)mDj8ManagerBle.needUpdateUserInfo2Front(needUpdateUserInfo2Front);
    }


    //开始工作
    public void startWork() {
        if (isWorkFlag){
            LogUtils.i(TAG,"ScaleManager已经在工作了");
            return;
        }
        isWorkFlag = true;
        scanBlueDevices();//扫描设备
        removeMessages(WHAT_AUTO_CHECK);
        sendEmptyMessageDelayed(WHAT_AUTO_CHECK, 6000);
    }

    public void stopWork() {
        stopAutoCheck();
        disConnectDevice(true);//断开连接
        isWorkFlag = false;
    }


    private static final int WHAT_RESTART_SCAN = 1;
    private static final int WHAT_AUTO_CHECK = 2;
    private static final int WHAT_START_SCAN = 3;

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        if (msg.what == WHAT_RESTART_SCAN) {
            LogUtils.i(TAG, "---收到重新扫描的指令");
            scanBlueDevices();
        } else if (msg.what == WHAT_AUTO_CHECK) {
            removeMessages(WHAT_AUTO_CHECK);
            sendEmptyMessageDelayed(WHAT_AUTO_CHECK, 7000);
            autoCheck();
        }else if (msg.what == WHAT_START_SCAN){
            if (mBlueScan!=null){
                LogUtils.i(TAG, "---收到开始扫描的指令");
                mBlueScan.startScanBluetoothDevices(mScanCallback);//开始扫描
            }
        }


    }

    //扫描蓝牙设备
    private void scanBlueDevices() {
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();//先停止扫描
        }
        removeMessages(WHAT_START_SCAN);
        sendEmptyMessageDelayed(WHAT_START_SCAN,1000);//停止一秒后再去扫描的意思

    }

    //扫描回调器
    private IScanCallback mScanCallback = new IScanCallback() {
        @Override
        public void beforeScan() {
            LogUtils.i(TAG, "---beforeScan---");
            device = null;
        }

        @Override
        public void scanOneDevice(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            post(new Runnable() {
                @Override
                public void run() {
                    recordScanDevice(device);
                }
            });

        }

        @Override
        public void overScan() {
            LogUtils.i(TAG, "---扫描结束---");
            if (device == null) {
                //说明没有扫描成功 需要重新扫描
                LogUtils.i(TAG, "---扫描结束 device = null");
//                removeMessages(WHAT_RESTART_SCAN);
//                sendEmptyMessageDelayed(WHAT_RESTART_SCAN, 3000);
            }
        }
    };

    private void recordScanDevice(BluetoothDevice device) {
       // if (device == null) {return;}
        String name = device.getName();
        String address = device.getAddress();
        LogUtils.i(TAG, "扫描到设备--Name = " + name + "---Addrss = " + address);
        if (Dj8Constant.Dj8_NAME.equals(name)){
            LogUtils.i(TAG, "--找到了需要连接的蓝牙设备------Name = " + name + "---Addrss = " + address + "---准备连接---");
            this.device = device;
            stopScan();//退出扫描
            connectBluetooth(device);//开始连接设备
        }



    }

    //连接蓝牙设备
    private void connectBluetooth(BluetoothDevice bluetoothDevice) {
        if (mDj8ManagerBle != null) {
            mDj8ManagerBle.connectDevice(bluetoothDevice);
        }
    }

//    private void connectBluetooth(String address) {
//        if (mDj8ManagerBle != null) {
//            mDj8ManagerBle.connectDevice(address);
//        }
//    }

    //自动检测机制
    private void autoCheck() {
        LogUtils.i(TAG, "自动检测 机制正在运行--autoCheck（）");

        if (mDj8ManagerBle == null) {
            LogUtils.i(TAG, "自动检测 mScaleProduct = null 此次 return");
            return;
        }

        if (mDj8ManagerBle.isConnect()) {
            LogUtils.i(TAG, "自动检测 设备--已经连接 此次return");
            return;
        }


        LogUtils.i(TAG, "自动检测 设备没有连接中 准备重新扫描连接");
        scanBlueDevices();



    }

    //初始化各个产品
    private void init(Context context) {

        mBlueScan = new BlueScan(context);
        mDj8ManagerBle = new Dj8ManagerBle(context);

        setListeners();
    }

    private void setListeners() {
        mDj8ManagerBle.setBlueConnectStationCallback(mConnectStationCallback);
        mDj8ManagerBle.setScaleMeasureCallback(mDj8MeasureCallback);
    }


    private IConnectStationCallback mIConnectStationCallback;
    public void setConnectStationCallback(IConnectStationCallback mIConnectStationCallback) {
        this.mIConnectStationCallback = mIConnectStationCallback;
    }


    private Dj8MeasureCallback dj8MeasureCallback;
    public void setScaleMeasureCallback(Dj8MeasureCallback dj8MeasureCallback) {
        this.dj8MeasureCallback = dj8MeasureCallback;
    }




    //退出释放
    public void exit() {
        //01 释放蓝牙扫描器
        if (mBlueScan != null) {
            if (mBlueScan.isScaningFlag) {
                mBlueScan.stopScanBluetoothDevices();
            }
            mBlueScan = null;
        }
        removeBluetoothStationListener(mIBlueStationListener);
        stopAutoCheck();
        if (mDj8ManagerBle!=null){
            mDj8ManagerBle.exit();
            mDj8ManagerBle = null;
        }
        dj8ScaleUserInfo = null;

    }

    private void stopAutoCheck() {
        removeMessages(WHAT_AUTO_CHECK);
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();//停止扫描
        }
    }



    String connectName;
    String connectAddress;
    //连接回调器
    private IConnectStationCallback mConnectStationCallback = new IConnectStationCallback() {
        @Override
        public void onConnected(ProductStyle productStyle, BluetoothDevice device) {
            if(device==null)return;
            connectName = device.getName();
            connectAddress = device.getAddress();
            LogUtils.i(TAG, "--连接成功--onConnected--device.name = " + connectName + "---device.address = " + connectAddress);
            setUpdateUser2Front(true);
          //  stopScan();//说明连接成功 退出扫描  这里注释掉意思是扫描到设备的时候已经停止扫描过了 没必要调用两次
            mDj8ManagerBle.setConnectName(connectName,connectAddress);

            if (mIConnectStationCallback != null) mIConnectStationCallback.onConnected(ProductStyle.DJ8,device);

        }

        @Override
        public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {
            if (mIConnectStationCallback != null) mIConnectStationCallback.onConnecting(ProductStyle.DJ8,device);
        }

        @Override
        public void onDisConnected(ProductStyle productStyle) {
            LogUtils.i(TAG, "-------------连接断开");
            if (mIConnectStationCallback != null) mIConnectStationCallback.onDisConnected(ProductStyle.DJ8);
        }

    };



    private Dj8MeasureCallback mDj8MeasureCallback = new Dj8MeasureCallback() {


        @Override
        public void onScaleWake(byte b0,byte b1) {
            LogUtils.i(TAG, "--------mDj8MeasureCallback---onScaleWake--秤唤醒 b0 = "+b0+"--b1 = "+b1);
            //B16连接成功的第一步同步时间
            //---------第一步：唤醒的第一步是同步时钟
            mDj8ManagerBle.syncSystemClock(0,b1);


            if (dj8MeasureCallback!=null)dj8MeasureCallback.onScaleWake(b0,b1);
        }

        @Override
        public void onScaleSleep() {
            LogUtils.i(TAG, "--------mDj8MeasureCallback---onScaleSleep--秤休眠");
            if (dj8MeasureCallback!=null)dj8MeasureCallback.onScaleSleep();
        }

        @Override
        public void onPowLow() {
            LogUtils.i(TAG, "--------mDj8MeasureCallback---onPowLow--秤电压低");
            if (dj8MeasureCallback!=null)dj8MeasureCallback.onPowLow();
        }

        @Override
        public void receiveTime(int model, String time, long time2) {
            LogUtils.i(TAG, "--------mDj8MeasureCallback---receiveTime--接收到秤时间 model="+model+"---time="+time+"---time2="+time2);
            //---------第二步：同步时钟完成以后的下一步是同步用户信息
            //设置时间model=0蓝牙 =1wifi
            // b0
            //0x00：设置当前APP的用户信息,新用户(只能蓝牙)
            //0x01：设置当前APP的用户信息,旧用户(只能蓝牙)
            //0x02：设置用户id的用户信息,新用户
            //0x03：设置用户id的用户信息,旧用户
            //0x04：获取用户id的用户信息
            //0x05：没有用户id的用户信息
           updateUserInfo(0,0x01);
           // mDj8ManagerBle.syncSystemClock(0,b111);
        }

        @Override
        public void setUserInfoSuccess() {
            //---------第三步：同步用户信息完成
            LogUtils.i(TAG, "--------mDj8MeasureCallback---setUserInfoSuccess--设置用户信息成功");
            if (dj8MeasureCallback!=null)dj8MeasureCallback.setUserInfoSuccess();
        }

        @Override
        public void onReceiveMeasureResult(Dj8MesureResult result) {
            LogUtils.i(TAG, "--------mDj8MeasureCallback---onReceiveMeasureResult--接收到测量信息 result="+result);
            //回ack和下发用户信息
            if (dj8MeasureCallback!=null)dj8MeasureCallback.onReceiveMeasureResult(result);


        }

        @Override
        public void onReceiveHisMeasureResult(Dj8MesureResult result) {
            LogUtils.i(TAG, "--------mDj8MeasureCallback---onReceiveMeasureResult--接收到 历史 测量信息 result="+result);
            if (dj8MeasureCallback!=null)dj8MeasureCallback.onReceiveHisMeasureResult(result);
        }

        @Override
        public void getHisDataFinish() {
            LogUtils.i(TAG, "--------mDj8MeasureCallback---getHisDataFinish--获取历史数据完成");
            if (dj8MeasureCallback!=null)dj8MeasureCallback.getHisDataFinish();
        }
    };

    private void stopScan() {
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();
        }
    }

    public boolean isConnected(){
        return mDj8ManagerBle!=null&&mDj8ManagerBle.isConnect();
    }
    public String getConnectAddrss(){
        if (mDj8ManagerBle!=null){
            return mDj8ManagerBle.getConnectBluetoothAddress();
        }
        return null;
    }
    private void disConnectDevice() {
        if (mDj8ManagerBle != null) mDj8ManagerBle.disConnect(true);
    }
    //断开连接 sendFront是否发给给前端的意思
    private void disConnectDevice(boolean sendFront) {
        if (mDj8ManagerBle != null) mDj8ManagerBle.disConnect(sendFront);
    }

    public boolean isSupportBluetooth(){
        return BlueManager.getInstance().isSupportBluetooth();
    }

    public boolean isBluetoothOpen(){
        return BlueManager.getInstance().isBluetoothOpen();
    }

    public void addBluetoothStationListener(IBlueStationListener listener){
        BlueManager.getInstance().addBluetoothStationListener(listener);
    }


    private IBlueStationListener mIBlueStationListener = new IBlueStationListener() {
        @Override
        public void STATE_OFF() {}

        @Override
        public void STATE_TURNING_OFF() {}

        @Override
        public void STATE_ON() {
            removeMessages(WHAT_AUTO_CHECK);
            sendEmptyMessageDelayed(WHAT_AUTO_CHECK, 0);
        }

        @Override
        public void STATE_TURNING_ON() {
        }
    };

    public void removeBluetoothStationListener(IBlueStationListener listener){
        BlueManager.getInstance().removeBluetoothStationListener(listener);
    }


    //更新用户信息
    //同步用户信息
    //设置时间model=0蓝牙 =1wifi
    // b0
    //0x00：设置当前APP的用户信息,新用户(只能蓝牙)
    //0x01：设置当前APP的用户信息,旧用户(只能蓝牙)
    //0x02：设置用户id的用户信息,新用户
    //0x03：设置用户id的用户信息,旧用户
    //0x04：获取用户id的用户信息
    //0x05：没有用户id的用户信息
    public void updateUserInfo(int model,int b0) {


        if (dj8ScaleUserInfo==null){
            LogUtils.i(TAG,"当前使用的用户信息为空 下发用户信息失败");
            return;
        }

        if (isConnected()){
            if (mDj8ManagerBle!=null){

                //同步用户信息
                //设置时间model=0蓝牙 =1wifi
                // b0
                //0x00：设置当前APP的用户信息,新用户(只能蓝牙)
                //0x01：设置当前APP的用户信息,旧用户(只能蓝牙)
                //0x02：设置用户id的用户信息,新用户
                //0x03：设置用户id的用户信息,旧用户
                //0x04：获取用户id的用户信息
                //0x05：没有用户id的用户信息

                //b1 用户id (0xff为访客模式)
                //role职业  (0:普通工作者 1:专业运动员)

                int userid = dj8ScaleUserInfo.getUserId();
                int age = dj8ScaleUserInfo.getAge();
                int sex = dj8ScaleUserInfo.getSex();
                int height = dj8ScaleUserInfo.getHeight();
                int role = dj8ScaleUserInfo.getRole();
                float weight = dj8ScaleUserInfo.getWeight();

                Dj8Users.getInstance().addUser(dj8ScaleUserInfo);//把此用户添加到用户池里面
                mDj8ManagerBle.syncUserInfo(model,b0,userid,age,sex,height,role,weight);
            }
        }

    }

//    //进入全险
//    public void jrqx(){
//        if (mDj8ManagerBle!=null){
//            mDj8ManagerBle.jrqx();
//        }
//    }
//    //退出全险
//    public void tchqx(){
//        if (mDj8ManagerBle!=null){
//            mDj8ManagerBle.tchqx();
//        }
//    }


//    public static float kg2lb(float kgValue){
//        return ScaleProduct.kg2lb(kgValue);
//    }
//
//    public static float lb2kg(float lbValue){
//        return ScaleProduct.lb2kg(lbValue);
//    }

    public boolean isWorkFlag() {
        return isWorkFlag;
    }


    public void setScaleUserInfo(Dj8ScaleUserInfo dj8ScaleUserInfo) {
        this.dj8ScaleUserInfo = dj8ScaleUserInfo;
        setUpdateUser2Front(true);
    }
}
